package com.jay.tools.web.webview;

import android.graphics.Bitmap;
import android.os.Handler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.jay.tools.configure.Party;
import com.jay.tools.utils.LogUtil;
import com.jay.tools.web.IPageLoadListener;
import com.jay.tools.web.WebFragment;
import com.jay.tools.web.route.Router;


/**
 * Created by tan on 2017/9/22 022.
 * WebViewClient针对浏览器本身进行控制
 */

public class WebViewClientImpl extends WebViewClient {

    private static final String TAG = "WebViewClientImpl";

    private final WebFragment WEB_FRAGMENT;
    private IPageLoadListener mIPageLoadListener;

    private Handler HANDLER = null;

    public WebViewClientImpl(WebFragment fragment) {
        this.WEB_FRAGMENT = fragment;
        HANDLER = Party.getHandler();
    }

    public void setPageLoadListener(IPageLoadListener listener) {
        this.mIPageLoadListener = listener;
    }

//    @Override
//    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//        return super.shouldOverrideUrlLoading(view, request);
//        // 高版本api才出现的方法，暂时不使用
//    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        LogUtil.e(TAG, "WebViewClient url == " + url);
        // 强制已经由WebView加载的页面中的url链接由原生进行接管
        return Router.getInstance().handleWebUrl(WEB_FRAGMENT, url);
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        if (null != mIPageLoadListener) {
            mIPageLoadListener.onLoadStart();
        }
//        LatteLoader.showLoading(view.getContext());
    }

    /**
     * 使APP像浏览器一样访问服务器
     */
    private void syncCookie() {
//        final String webHost = (String) Latte.getConfigurations().get(ConfigKeys.WEB_HOST);
//        if (null == webHost || "".equals(webHost)) {
//            return;
//        }
//        final CookieManager cookieManager = CookieManager.getInstance();
//        if (cookieManager.hasCookies()) {
//            final String cookieStr = cookieManager.getCookie(webHost);
//            if (null != cookieStr && !"".equals(cookieStr)) {
//                LattePreference.addCustomAppProfile(AddCookieIntercepter.COOKIE_KEY, cookieStr);
//            }
//        }

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        syncCookie();
        if (null != mIPageLoadListener) {
            mIPageLoadListener.onLoadEnd();
        }
//        HANDLER.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                LatteLoader.stopLoading();
//            }
//        }, Latte.getLoaderDelayed());
    }
}
